package me.zhengjie.modules.system.rest;/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.zhengjie.modules.poker.PokerFormatUtil;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.PokerActivateInfoQueryCriteria;
import me.zhengjie.modules.system.domain.vo.PokerActivateInfoVO;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author greazy
* @date 2025-04-07
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "activate")
@RequestMapping("/api/pokerActivateInfo")
public class PokerActivateInfoController {

    private final PokerActivateInfoService pokerActivateInfoService;
    private final PokerUserActivatInfoService userActivatInfoService;
    private final PokerAwardService awardService;
    private final KingTeamVoteService kingTeamVoteService;
    private final KingTeamService kingTeamService;
    private final AutoPokerActivateConfigService configService;

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('pokerActivateInfo:list')")
    public void exportPokerActivateInfo(HttpServletResponse response, PokerActivateInfoQueryCriteria criteria) throws IOException {
        pokerActivateInfoService.download(pokerActivateInfoService.queryAll(criteria), response);
    }

    @GetMapping
    @ApiOperation("查询activate")
    @PreAuthorize("@el.check('pokerActivateInfo:list')")
    public ResponseEntity<PageResult<PokerActivateInfo>> queryPokerActivateInfo(PokerActivateInfoQueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        return new ResponseEntity<>(pokerActivateInfoService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增activate")
    @ApiOperation("新增activate")
    @PreAuthorize("@el.check('pokerActivateInfo:add')")
    public ResponseEntity<Object> createPokerActivateInfo(@Validated @RequestBody PokerActivateInfo resources){
        pokerActivateInfoService.create(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改activate")
    @ApiOperation("修改activate")
    @PreAuthorize("@el.check('pokerActivateInfo:edit')")
    public ResponseEntity<Object> updatePokerActivateInfo(@Validated @RequestBody PokerActivateInfo resources){
        pokerActivateInfoService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除activate")
    @ApiOperation("删除activate")
    @PreAuthorize("@el.check('pokerActivateInfo:del')")
    public ResponseEntity<Object> deletePokerActivateInfo(@ApiParam(value = "传ID数组[]") @RequestBody List<Integer> ids) {
        pokerActivateInfoService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @AnonymousPostMapping("/s")
    public ResponseEntity<Object> startActivate(Integer id){
        pokerActivateInfoService.startActivate(id);
        return new ResponseEntity<>(HttpStatus.CREATED);

    }

    @AnonymousGetMapping("/random")
    public ResponseEntity<Object> random(){
        String randomCard = PokerFormatUtil.getRandomCard();
        return new ResponseEntity<>(randomCard,HttpStatus.OK);

    }

    @AnonymousGetMapping("/activateList")
    public ResponseEntity<Object> activateList(Integer serverId,Integer runStatus){
        Long userId = SecurityUtils.getCurrentUserId();
        LambdaQueryWrapper<PokerActivateInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerActivateInfo::getRunStatus,runStatus).eq(PokerActivateInfo::getActivateType,0);
        if (ObjectUtil.isNotEmpty(serverId)){
            wrapper.eq(PokerActivateInfo::getServerId,serverId);
        }
        wrapper.orderByDesc(PokerActivateInfo::getEndTime);
        List<PokerActivateInfo> list = pokerActivateInfoService.list(wrapper);

        ArrayList<PokerActivateInfoVO> pokerActivateInfoVOS = new ArrayList<>();
        for (PokerActivateInfo pokerActivateInfo : list) {

            LambdaQueryWrapper<PokerUserActivatInfo> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(PokerUserActivatInfo::getTaskId,pokerActivateInfo.getTaskId())
                    .eq(PokerUserActivatInfo::getUserId,userId)
                    .eq(PokerUserActivatInfo::getActivateId,pokerActivateInfo.getId());
            PokerUserActivatInfo one = userActivatInfoService.getOne(wrapper1);

            PokerActivateInfoVO pokerActivateInfoVO = new PokerActivateInfoVO();
            BeanUtil.copyProperties(pokerActivateInfo,pokerActivateInfoVO,true);
            if (ObjectUtil.isNotEmpty(one)){
                pokerActivateInfoVO.setIsJoin(1);
                pokerActivateInfoVO.setRank(one.getRank());
            }else{
                pokerActivateInfoVO.setIsJoin(0);
            }

            LambdaQueryWrapper<PokerAward> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(PokerAward::getTaskId,pokerActivateInfo.getTaskId())
                    .eq(PokerAward::getUserId,userId);
            List<PokerAward> listAward = awardService.list(wrapper2);

            pokerActivateInfoVO.setIsAward(1);
            long count = listAward.stream().filter(item -> item.getIsEnd() == 0).count();
            if (!listAward.isEmpty()){
                pokerActivateInfoVO.setIsAward(1);
            }else{
                pokerActivateInfoVO.setIsAward(0);
            }
            if (count>0){
                pokerActivateInfoVO.setAwardCount(count);
            }else{
                pokerActivateInfoVO.setAwardCount(0L);
            }

            pokerActivateInfoVOS.add(pokerActivateInfoVO);
        }
        return new ResponseEntity<>(pokerActivateInfoVOS,HttpStatus.OK);
    }


    @AnonymousGetMapping("/activateListKing")
    public ResponseEntity<Object> activateListKing(Integer serverId,Integer runStatus){
        Long userId = SecurityUtils.getCurrentUserId();
        LambdaQueryWrapper<PokerActivateInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerActivateInfo::getRunStatus,runStatus).eq(PokerActivateInfo::getActivateType,1);
        if (ObjectUtil.isNotEmpty(serverId)){
            wrapper.eq(PokerActivateInfo::getServerId,serverId);
        }
        wrapper.orderByDesc(PokerActivateInfo::getEndTime);
        List<PokerActivateInfo> list = pokerActivateInfoService.list(wrapper);

        ArrayList<PokerActivateInfoVO> pokerActivateInfoVOS = new ArrayList<>();
        for (PokerActivateInfo pokerActivateInfo : list) {

            LambdaQueryWrapper<KingTeamVote> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(KingTeamVote::getActivateId,pokerActivateInfo.getId())
                    .eq(KingTeamVote::getUserId,userId);
            KingTeamVote one = kingTeamVoteService.getOne(wrapper1);

            PokerActivateInfoVO pokerActivateInfoVO = new PokerActivateInfoVO();
            BeanUtil.copyProperties(pokerActivateInfo,pokerActivateInfoVO,true);
            if (ObjectUtil.isNotEmpty(one)){
                pokerActivateInfoVO.setIsJoin(1);
                pokerActivateInfoVO.setRank(one.getRank());
                KingTeam team = kingTeamService.getById(one.getGroupId());
                pokerActivateInfoVO.setTeamName(team.getGroupName());
            }else{
                pokerActivateInfoVO.setIsJoin(0);
            }



            LambdaQueryWrapper<PokerAward> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(PokerAward::getTaskId,pokerActivateInfo.getTaskId())
                    .eq(PokerAward::getUserId,userId);
            List<PokerAward> listAward = awardService.list(wrapper2);

            pokerActivateInfoVO.setIsAward(1);
            long count = listAward.stream().filter(item -> item.getIsEnd() == 0).count();
            if (!listAward.isEmpty()){
                pokerActivateInfoVO.setIsAward(1);
            }else{
                pokerActivateInfoVO.setIsAward(0);
            }
            if (count>0){
                pokerActivateInfoVO.setAwardCount(count);
            }else{
                pokerActivateInfoVO.setAwardCount(0L);
            }

            pokerActivateInfoVOS.add(pokerActivateInfoVO);
        }
        return new ResponseEntity<>(pokerActivateInfoVOS,HttpStatus.OK);
    }

    @AnonymousPostMapping("/e")
    public ResponseEntity<Object> endActivate(Integer id ){
        pokerActivateInfoService.endActivate(id);
        return new ResponseEntity<>("结算完成",HttpStatus.OK);

    }

    @AnonymousPostMapping("/eKing")
    public ResponseEntity<Object> eKing(Integer activateId,Integer rankGroupId,Integer[] joinGroupIds ){
        List<Integer> list = Arrays.asList(joinGroupIds);
        pokerActivateInfoService.eKing(activateId,rankGroupId,list);
        return new ResponseEntity<>("结算完成",HttpStatus.OK);

    }

    @AnonymousPostMapping("/testTaskGen")
    public ResponseEntity<Object> testTaskGen( ){
        configService.autoGenPokerActivate();
        return new ResponseEntity<>("生成",HttpStatus.OK);

    }

    }